package com.jams.goodox.activity.serve.enterprise;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hangzhou.jin.customview.TextMoreLayout;
import com.jams.goodox.BaseActivity;
import com.jams.goodox.R;
import com.jams.goodox.SePref;
import com.jams.goodox.activity.common.SimpleHtmlActivity;
import com.jams.goodox.entity.ProjectFinancialItem;
import com.jams.goodox.entity.resp.EnterpriseFieldResp;
import com.jams.goodox.entity.resp.EnterpriseStageResp;
import com.jams.goodox.entity.resp.ProjectFinancialDetailResp;
import com.jams.goodox.entity.resp.ProjectTypeResp;
import com.jams.goodox.net.BaseEntity;
import com.jams.goodox.net.RetrofitCallbackListener;
import com.jams.goodox.net.services.EnterpriseService;
import com.jams.goodox.utils.CollectionUtils;
import com.jams.goodox.utils.DensityUtil;
import com.jams.goodox.utils.StringUtils;
import com.jams.goodox.utils.StyleUtil;
import com.jams.goodox.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import retrofit2.Call;

import static com.jams.goodox.activity.serve.enterprise.ChooseListForProjectFinancialActivity.CHOOSE_FINANCIAL;
import static com.jams.goodox.activity.serve.enterprise.ChooseListForProjectFinancialActivity.CONTENT_FINANCIAL;
import static com.jams.goodox.activity.serve.enterprise.ChooseListForProjectFinancialActivity.RESULT_CODE_PROJECT_FINANCIAL;
import static com.jams.goodox.activity.serve.enterprise.ChooseListForProjectFinancialActivity.TITLE_FINANCIAL;


/**
 * 项目融资
 */
public class ProjectFinancingActivity extends BaseActivity {
    @Bind(R.id.sdv_banner)
    SimpleDraweeView ivBanner;
    @Bind(R.id.tl_company_status)
    TextMoreLayout tlCompanyStatus;
    @Bind(R.id.ll_project_name)
    LinearLayout llProjectName;
    @Bind(R.id.tv_project_name_content)
    TextView tvName;
    @Bind(R.id.tl_which_field)
    TextMoreLayout tlWhichField;
    @Bind(R.id.tl_project_type)
    TextMoreLayout tlProjectType;
    @Bind(R.id.ll_project_summarize)
    LinearLayout llProjectSummarize;
    @Bind(R.id.tv_project_summarize_content)
    TextView tvSummarize;
    @Bind(R.id.tv_business_plan)
    TextView tvBusinessPlan;
    @Bind(R.id.tv_submit)
    TextView tvSubmit;


    /**
     * 公司所处阶段
     */
    private String stageId;
    private final int STAGE_REQUEST = 100;
    private String stageContent;
    /**
     * 项目类型
     */
    private String typeId ;
    private final int TYPE_REQUEST = 101;
    private String typeContent ;
    /**
     * 所属领域
     */
    private String fieldId ;
    private final int FIELD_REQUEST = 102;
    private String fieldContent ;
    /**
     * 项目名称
     */
   // private int namePosition = -1;
    private final int NAME_REQUEST = 103;
    private String nameContent = "";
    /**
     * 项目概述
     */
    //private int summarizePosition = -1;
    private final int SUMMARIZE_REQUEST = 104;
    /**
     * 项目概述
     */
    private String summarizeContent;
    private EnterpriseService service = createCallService(EnterpriseService.class);
    /**
     * 发送商业计划书的邮箱
     */
    private String email;
    /**
     * 公司所处阶段
     */
    private List<EnterpriseStageResp.DataBean> stageList = new ArrayList<>();
    /**
     * 所属领域
     */
    private List<EnterpriseFieldResp.DataBean> domainList = new ArrayList<>();
    /**
     * 项目类型
     */
    private List<ProjectTypeResp.DataBean> typeList = new ArrayList<>();
    /**
     *公司所处阶段(id+name)
     */
    private ArrayList<ProjectFinancialItem> stageIdNameList = new ArrayList<>();
    /**
     *公司所属领域(id+name)
     */
    private ArrayList<ProjectFinancialItem> domainIdNameList = new ArrayList<>();
    /**
     *公司所项目类型(id+name)
     */
    private ArrayList<ProjectFinancialItem> typeIdNameList = new ArrayList<>();

    /**
     * 焦点图链接
     */
    private String picSuperLink;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_project_finance;
    }

    @Override
    protected void init() {
        StyleUtil.titleBackKey(this, getResources().getString(R.string.project_financing));
        setBanner();
        getProjectDetail();
    }

    /**
     * 设置图片高度
     */
    private void setBanner() {
        ViewGroup.LayoutParams params = ivBanner.getLayoutParams();
        //高度是宽度的3/8
        params.height = (int) (DensityUtil.getDisplayWidth(mContext) * 0.375);
        ivBanner.setLayoutParams(params);
        GenericDraweeHierarchy hierarchy = ivBanner.getHierarchy();
        hierarchy.setPlaceholderImage(R.mipmap.banner_project_financing); //默认banner图
        
    }

    /**
     * 商业计划书的内容添加邮箱
     */
    private void setEmail() {
        String emailAddress = getResources().getString(R.string.business_plan);
        StringBuilder sb = new StringBuilder(emailAddress);
        sb.insert(sb.indexOf("我们"), email);
        tvBusinessPlan.setText(sb);
    }


    @OnClick({R.id.tl_company_status, R.id.ll_project_name, R.id.tl_which_field, R.id.tl_project_type, R.id.ll_project_summarize, R.id.tv_submit,R.id.sdv_banner})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            //所处阶段
            case R.id.tl_company_status:
                getEnterpriseStage();
                break;
            //项目名称
            case R.id.ll_project_name:
                intent = new Intent(this, ProjectNameAndSummarizeActivity.class);
                intent.putExtra(TITLE_FINANCIAL, "项目名称");
                intent.putExtra("CONTENT", nameContent);
                startActivityForResult(intent, NAME_REQUEST);
                break;
            //所属领域
            case R.id.tl_which_field:
                getEnterpriseDomain();
                break;
            //项目类型
            case R.id.tl_project_type:
                getEnterpriseProjectType();
                break;
            //项目概述
            case R.id.ll_project_summarize:
                intent = new Intent(this, ProjectNameAndSummarizeActivity.class);
                intent.putExtra(TITLE_FINANCIAL, "项目概述");
                intent.putExtra("CONTENT", summarizeContent);
                startActivityForResult(intent, SUMMARIZE_REQUEST);
                break;
            //提交
            case R.id.tv_submit:
                if (TextUtils.isEmpty(stageContent) ||
                        TextUtils.isEmpty(nameContent) ||
                        TextUtils.isEmpty(fieldContent) ||
                        TextUtils.isEmpty(typeContent) ||
                        TextUtils.isEmpty(summarizeContent)) {
                    ToastUtil.show(mContext, R.string.complete_the_information_and_submit);
                    return;
                }
                submit();
                break;
            //点击焦点图,跳转
            case R.id.sdv_banner:
                if (TextUtils.isEmpty(picSuperLink)) {
                   return; 
                }
                intent = new Intent(mContext,SimpleHtmlActivity.class);
                intent.putExtra(SimpleHtmlActivity.URL,picSuperLink);
                intent.putExtra(SimpleHtmlActivity.TITLE,"详情");
                qStartActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_CODE_PROJECT_FINANCIAL) {
            switch (requestCode) {
                case STAGE_REQUEST:
                    if (data != null) {
                        ProjectFinancialItem chooseItem = (ProjectFinancialItem) data.getSerializableExtra(CHOOSE_FINANCIAL);
                        tlCompanyStatus.setRightText(StringUtils.newString(chooseItem.name));
                        stageId = StringUtils.newString(chooseItem.id);
                        stageContent = StringUtils.newString(chooseItem.name);
                    }
                    break;
                case TYPE_REQUEST:
                    if (data != null) {
                        ProjectFinancialItem chooseItem = (ProjectFinancialItem) data.getSerializableExtra(CHOOSE_FINANCIAL);
                        tlProjectType.setRightText(StringUtils.newString(chooseItem.name));
                        typeId = StringUtils.newString(chooseItem.id);
                        typeContent = StringUtils.newString(chooseItem.name);
                    }
                    break;
                case FIELD_REQUEST:
                    if (data != null) {
                        ProjectFinancialItem chooseItem = (ProjectFinancialItem) data.getSerializableExtra(CHOOSE_FINANCIAL);
                        tlWhichField.setRightText(StringUtils.newString(chooseItem.name));
                        fieldId = StringUtils.newString(chooseItem.id);
                        fieldContent = StringUtils.newString(chooseItem.name);
                    }
                    break;
                case NAME_REQUEST:
                    if (data != null) {
                        String content = StringUtils.newString(data.getStringExtra(CHOOSE_FINANCIAL));
                        tvName.setText(content);
                        nameContent = content;
                    }
                    break;
                case SUMMARIZE_REQUEST:
                    if (data != null) {
                        String content = StringUtils.newString(data.getStringExtra(CHOOSE_FINANCIAL));
                        tvSummarize.setText(content);
                        summarizeContent = content;
                    }
                    break;
            }
        }
    }

    /**
     * 公司所处阶段列表,有数据直接跳转,无数据,请求成功后跳转
     **/

    private void getEnterpriseStage() {
        if (CollectionUtils.hasData(stageIdNameList)) {
            Intent  intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
            intent.putExtra(TITLE_FINANCIAL, "公司所处阶段");
            intent.putExtra(CHOOSE_FINANCIAL, stageIdNameList);
            intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(stageContent));
            startActivityForResult(intent, STAGE_REQUEST);
            return;
        }
        showLoading();
        enqueue(service.getEnterpriseStage(), new RetrofitCallbackListener<EnterpriseStageResp>() {
            @Override
            public void onSuccess(Call<EnterpriseStageResp> call, EnterpriseStageResp result) {
                misLoading();
                try {
                    stageIdNameList.clear();
                    stageList = result.data;
                    for (EnterpriseStageResp.DataBean bean: stageList) {
                        ProjectFinancialItem  item = new ProjectFinancialItem(bean.levelId,bean.levelName);
                        stageIdNameList.add(item);
                    }
                    Intent  intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
                    intent.putExtra(TITLE_FINANCIAL, "公司所处阶段");
                    intent.putExtra(CHOOSE_FINANCIAL, stageIdNameList);
                    intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(stageContent));
                    startActivityForResult(intent, STAGE_REQUEST);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }

    /**
     * 公司所属领域
     */
    private void getEnterpriseDomain() {
        if (CollectionUtils.hasData(domainIdNameList)) {
            Intent intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
            intent.putExtra(TITLE_FINANCIAL, "所属领域");
            intent.putExtra(CHOOSE_FINANCIAL, domainIdNameList);
            intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(fieldContent));
            startActivityForResult(intent, FIELD_REQUEST);
            return;
        }
        showLoading();
        enqueue(service.getEnterpriseDomain(), new RetrofitCallbackListener<EnterpriseFieldResp>() {
            @Override
            public void onSuccess(Call<EnterpriseFieldResp> call, EnterpriseFieldResp result) {
                misLoading();
                try {
                    domainIdNameList.clear();
                    domainList = result.data;
                    for (EnterpriseFieldResp.DataBean bean: domainList) {
                        ProjectFinancialItem  item = new ProjectFinancialItem(bean.domainId,bean.domainName);
                        domainIdNameList.add(item);
                    }
                    Intent  intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
                    intent.putExtra(TITLE_FINANCIAL, "所属领域");
                    intent.putExtra(CHOOSE_FINANCIAL, domainIdNameList);
                    intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(fieldContent));
                    startActivityForResult(intent, FIELD_REQUEST);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }



    /**
     * 公司项目类型
     */
    private void getEnterpriseProjectType() {
        if (CollectionUtils.hasData(typeIdNameList)) {
            Intent  intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
            intent.putExtra(TITLE_FINANCIAL, "项目类型");
            intent.putExtra(CHOOSE_FINANCIAL, typeIdNameList);
            intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(typeContent));
            startActivityForResult(intent, TYPE_REQUEST);
            return;
        }
        showLoading();
        enqueue(service.getEnterpriseProjectType(), new RetrofitCallbackListener<ProjectTypeResp>() {
            @Override
            public void onSuccess(Call<ProjectTypeResp> call, ProjectTypeResp result) {
                misLoading();
                try {
                    typeList = result.data;
                    typeIdNameList.clear();
                    for (ProjectTypeResp.DataBean bean: typeList) {
                        ProjectFinancialItem  item = new ProjectFinancialItem(bean.projectTypeId,bean.projectTypeName);
                        typeIdNameList.add(item);
                    }
                    Intent  intent = new Intent(mContext, ChooseListForProjectFinancialActivity.class);
                    intent.putExtra(TITLE_FINANCIAL, "项目类型");
                    intent.putExtra(CHOOSE_FINANCIAL, typeIdNameList);
                    intent.putExtra(CONTENT_FINANCIAL, StringUtils.newString(typeContent));
                    startActivityForResult(intent, TYPE_REQUEST);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }
    /**
     * 项目融资情况
     */
    private void getProjectDetail() {
        //默认是false
        setEnable(false);
        showLoading();
        enqueue(service.getProjectDetail(), new RetrofitCallbackListener<ProjectFinancialDetailResp>() {
            @Override
            public void onSuccess(Call<ProjectFinancialDetailResp> call, ProjectFinancialDetailResp result) {
                misLoading();
                try {
                    email = StringUtils.newString(result.data.email);
                    ivBanner.setImageURI(StringUtils.newString(result.data.focusPic));
                    picSuperLink = StringUtils.newString(result.data.picSuperLink);
                    setEmail();
                    if (result.data.projectDetail == null) {
                        //未提交过信息
                        setEnable(true);
                    } else {
                        //已提交过信息
                        setEnable(false);
                        //所属阶段
                        tlCompanyStatus.setRightText(result.data.projectDetail.companyLevelName);
                        stageContent = StringUtils.newString(result.data.projectDetail.companyLevelName);
                        //项目名称
                        tvName.setText(result.data.projectDetail.projectName);
                        nameContent = StringUtils.newString(result.data.projectDetail.projectName);
                        //所属领域
                        tlWhichField.setRightText(result.data.projectDetail.domainName);
                        fieldContent = StringUtils.newString(result.data.projectDetail.domainName);
                        //项目类型
                        tlProjectType.setRightText(result.data.projectDetail.projectTypeName);
                        typeContent = StringUtils.newString(result.data.projectDetail.projectTypeName);
                        //项目概述
                        tvSummarize.setText(result.data.projectDetail.introduce);
                        summarizeContent = StringUtils.newString(result.data.projectDetail.introduce);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String msg) {
                misLoading();
            }
        });
    }
    /**
     * 项目融资提交
     */
    private void submit() {
        showLoading();
        Map<String,String> params = new HashMap<>();
        params.put("domainId",fieldId);
        params.put("introduce",summarizeContent);
        params.put("levelId",stageId);
        params.put("projectName",nameContent);
        params.put("projectTypeId",typeId);
        params.put("userId",SePref.getUserId());
        enqueue(service.submitProjectFinancial(params), new RetrofitCallbackListener<BaseEntity>() {
            @Override
            public void onSuccess(Call<BaseEntity> call, BaseEntity result) {
                misLoading();
                ToastUtil.show(mContext, R.string.submit_completed_send_plan_to_email);
                finish();
            }

            @Override
            public void onError(String msg) {
                misLoading();
                ToastUtil.show(mContext,"提交失败");
            }
        });
    }

    /**
     * 设置 view 是否enable
     */
    private void setEnable(boolean isEnable) {
        tlCompanyStatus.setEnabled(isEnable);
        llProjectName.setEnabled(isEnable);
        tlWhichField.setEnabled(isEnable);
        tlProjectType.setEnabled(isEnable);
        llProjectSummarize.setEnabled(isEnable);
        tvSubmit.setEnabled(isEnable);
    }




}
